import { AssetManager, JsonAsset } from "cc";
import { Singleton } from "./Singleton";
import { LoaderManager } from "./LoaderManager";
import { LoaderBundle } from "./LoaderBundle";
import GameUtils from "../tools/GameUtils";
import { SystemParams } from "./SystemParams";
import { Logger } from "../log/Logger";

export class I18Manager extends Singleton{
    private _bundle:AssetManager.Bundle;
    private _language:string="en"
    private _languageJSONPkg:any;

    protected init(): void {
        
    }
    public setJSON(json:any){
        this._languageJSONPkg=json
    }
    public getLanguage():string{
        return this._language
    }
    /**
     * 设置当前语言
     * @param lang 
     */
    public setLanguage(lang:string){
        if(this._language != lang){
            this._language=lang
            const url:string=GameUtils.getBundlePath(this._language)
            const ver:string=SystemParams.getInstance().getBundleVerison(this._language)
            LoaderManager.getInstance().loadBundle(url, {version:ver},null,(bundle:LoaderBundle)=>{
                if(bundle){
                    this._bundle=bundle.bundle
                    this._bundle.load("language",(err:Error,data:JsonAsset)=>{
                        !err ? I18Manager.getInstance().setJSON(data.json) : Logger.Error(err.message)
                    })
                }
                else{
                    Logger.Error(`当前语言加载错误..【${this._language}】..`)
                }
            })
        }
    }

    public getString(path:string):Promise<string>{
        return new Promise(async resolve=>{
            let langStr:string = ""
            if(this._languageJSONPkg && this._languageJSONPkg[path])langStr = (this._languageJSONPkg[path].value)
            else{
                Logger.error(`......当前语言key=${path}获取失败.......`)
            }
            resolve(langStr);
        })
    }

}